package com.zhhtech.zhh.ui.helper

import android.content.Context
import com.github.gzuliyujiang.oaid.DeviceID
import com.github.gzuliyujiang.oaid.IGetter
import com.lxj.xpopup.XPopup
import com.zhhtech.zhh.bean.CaseConfig
import com.zhhtech.zhh.common.WX_APP_ID
import com.zhhtech.zhh.ui.activity.commom.openSystemUrl
import com.zhhtech.zhh.ui.dialog.WeComDialog
import com.zhhtech.zhh.ui.dialog.showAlertDialog
import com.zhhtech.zhh.ui.utils.Logger
import com.zhhtech.zhh.ui.utils.SPUtils
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram
import com.tencent.mm.opensdk.modelbiz.WXOpenCustomerServiceChat
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.zhhtech.zhh.ui.ext.toastMessageLong
import kotlinx.coroutines.suspendCancellableCoroutine
import java.util.UUID
import kotlin.coroutines.resume

const val KEY_IMEI = "KEY_IMEI"

/**
 * 这个方法一定要在启动页执行完之后执行
 */
fun getImei() = SPUtils.getString(KEY_IMEI)
suspend fun getImeiSuspend(context: Context): String {
    val imei = SPUtils.getString(KEY_IMEI)
    return imei.ifEmpty {
//        DemoHelper.certPem = com.zhhtech.zhh.api.API_SERVICE.cert().byteString().utf8()
        val imei = suspendCancellableCoroutine { coroutin ->
            getImei(context) {
                coroutin.resume(it)
            }
        }
        imei
    }
}

fun getImei(context: Context, callback: (imei: String) -> Unit) {
    val imei = SPUtils.getString(KEY_IMEI)
    if (imei.isEmpty()) {
//        DemoHelper { oaid ->
//            Logger.e("OAID==>${oaid}")
//            val imei = oaid ?: uuid()
//            SPUtils.put(KEY_IMEI, imei)
//            callback.invoke(imei)
//        }.getDeviceIdsWithRequestPermission(context)
        if (DeviceID.supportedOAID(context)) {
            DeviceID.getOAID(context, object : IGetter {
                override fun onOAIDGetComplete(result: String?) {
                    Logger.e("OAID==>${result}")
                    val imei = result ?: uuid()
                    SPUtils.put(KEY_IMEI, imei)
                    callback.invoke(imei)
                }

                override fun onOAIDGetError(error: Exception?) {
                    val imei = uuid()
                    SPUtils.put(KEY_IMEI, imei)
                    callback.invoke(imei)
                }
            })
        } else {
            val imei = uuid()
            SPUtils.put(KEY_IMEI, imei)
            callback.invoke(imei)
        }
    } else {
        callback.invoke(imei)
    }
}

fun uuid() = UUID.randomUUID().toString().replace("-", "")

/**
 * 打开微信客服
 */
fun Context.openWorkKf() {
    val api: IWXAPI = WXAPIFactory.createWXAPI(this, WX_APP_ID)
    // 判断当前版本是否支持拉起客服会话
    if (api.isWXAppInstalled) {
        if (api.wxAppSupportAPI >= com.tencent.mm.opensdk.constants.Build.SUPPORT_OPEN_CUSTOMER_SERVICE_CHAT) {
            val req = WXOpenCustomerServiceChat.Req()
            // 企业ID
            req.corpId = "wwcaa2bb0326ddefbe"
            // 客服URL
            req.url = "https://work.weixin.qq.com/kfid/kfc95d9fa49d562474d"
            api.sendReq(req)
        } else {
            "无法拉起微信客服，请电话联系客服！".toastMessageLong()
        }
    } else {
        "未安装微信APP，无法唤起微信客服，请电话联系客服或者安装微信app！".toastMessageLong()
    }
}

fun ILoa.jumpWx(config: CaseConfig?) {
    if (config?.jump != null) {
        if (config.jump.type == 1) {
            mLoaContext?.openSystemUrl(config.jump.link)
        } else if (config.jump.type == 2) {
            val appId = WX_APP_ID
            val api = WXAPIFactory.createWXAPI(mLoaContext?.applicationContext, appId)
            val req = WXLaunchMiniProgram.Req()
            req.userName = config.jump.userName
            req.path = config.jump.path
            req.miniprogramType = config.jump.miniprogramType
            Logger.e("req.path==>${req.path}")
            api.sendReq(req)
        } else if (config.jump.type == 3) {
            mBaseActivity?.showAlertDialog {
                message("请联系客服！")
                negativeButton("我知道了") { }
                positiveButton("联系客服") {
                    val mWeComDialog = WeComDialog(mLoaContext!!, config.weComImg, config.phone)
                    XPopup.Builder(context)
                        .isDestroyOnDismiss(true)
                        .asCustom(mWeComDialog)
                        .show()
                }
            }
        }
    }
}